"""
MIT License

Copyright (c) 2022 zeroday0619 <zeroday0619_dev@outlook.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import os
import glob
import logging
import re # regex
import zipfile
from shutil import copyfile, copytree

logging.basicConfig(format=logging.BASIC_FORMAT, level=logging.INFO)
logger = logging.getLogger("lutris_packaging.py")


# Newest patch has the "patch.sh" script inside
def get_patch_ver():
    files = glob.glob("../???/patch.sh")
    assert len(files) == 1, "Found too many patch versions"
    match = re.match(".*/(\d+)/.*", files[0])
    return match.group(1)

work_dir = os.getcwd()
patch_version = get_patch_ver()
logger.info(f"Packing for version {patch_version}")

# Destination directory for zipping
dst_dir = f"{work_dir}/gi_patch_{patch_version}"
dst_dir_files = f"{dst_dir}/patch_files"

# Patch source files
src_dir = f"{work_dir}/../{patch_version}"
src_dir_files = f"{src_dir}/patch_files"


def my_mkdir(path):
    if not os.path.exists(path):
        logger.info(f"create dir -> {path}")
        os.makedirs(path)
    else:
        logger.warning(f"already exist -> {path}")

class CreateDirFaild(OSError):
    pass

def mkdir_gi_patch():
    try:
        my_mkdir(dst_dir)
        my_mkdir(dst_dir_files)
    except OSError:
        raise CreateDirFaild()

def my_copyfile(src, dst):
    src_rel = os.path.relpath(src)
    dst_rel = os.path.relpath(dst)
    logger.info(f"copy {src_rel} -> {dst_rel}")
    copyfile(f"{src}", f"{dst}")

def copy_gi_patch():
    if not os.path.exists(src_dir):
        logger.error(f"Directory is not found -> {src_dir}")
        raise NotADirectoryError()

    my_copyfile(f"{src_dir}/patch.sh", f"{dst_dir}/patch.sh")
    my_copyfile(f"{src_dir}/patch_anti_logincrash.sh", f"{dst_dir}/patch_anti_logincrash.sh")
    my_copyfile(f"{src_dir}/patch_revert.sh", f"{dst_dir}/patch_revert.sh")

    copytree(src_dir_files, dst_dir_files, dirs_exist_ok=True)
    logger.info(f"copy {src_dir_files} -> {dst_dir_files}")


# Scripts for integration with the Lutris configuration file
template_apatch="""#!/bin/bash
DRIVE_C="$(pwd)/.."

cd "$DRIVE_C/Program Files/Genshin Impact/Genshin Impact game/"
bash "$DRIVE_C/gi_patch/patch.sh"
bash "$DRIVE_C/gi_patch/patch_anti_logincrash.sh"
echo "Press enter to close this window..."
read a
"""

template_rpatch="""#!/bin/bash
DRIVE_C="$(pwd)/.."

cd "$DRIVE_C/Program Files/Genshin Impact/Genshin Impact game/"
bash "$DRIVE_C/gi_patch/patch_revert.sh"
echo "Press enter to close this window..."
read a
"""

def opener(path, flags):
    return os.open(path, flags, 0o777)

def create_scripts():
    os.umask(0) # why is this needed?

    if not os.path.exists(f'{dst_dir}/ex_apatch.sh'):
        logger.info(f"create scripts -> {dst_dir}/ex_apatch.sh")
        with open(f'{dst_dir}/ex_apatch.sh', 'a', opener=opener) as ex_apatch:
            ex_apatch.write(template_apatch)
    else:
        logger.warning(f"already exist -> {dst_dir}/ex_apatch.sh")

    if not os.path.exists(f'{dst_dir}/ex_rpatch.sh'):
        logger.info(f"create scripts -> {dst_dir}/ex_rpatch.sh")
        with open(f'{dst_dir}/ex_rpatch.sh', 'a', opener=opener) as ex_rpatch:
            ex_rpatch.write(template_rpatch)
    else:
        logger.warning(f"already exist -> {dst_dir}/ex_rpatch.sh")


def compression():
    logger.info("Compression start")
    zip_f = zipfile.ZipFile(f"gi_patch_{patch_version}.zip", "w")
    os.chdir(dst_dir)
    for (path, dir, files) in os.walk(dst_dir):
        for file in files:
            logger.info(f"Add to archive: {os.path.relpath(path, dst_dir)}/{file}")
            zip_f.write(os.path.join(os.path.relpath(path, dst_dir), file), compress_type=zipfile.ZIP_DEFLATED)
    zip_f.close()
    logger.info(f"Compression complete: gi_patch_{patch_version}.zip")


mkdir_gi_patch()
copy_gi_patch()
create_scripts()
compression()
